<template>
  <div>
      <el-form ref="formObj" :rules="rules" :model="role" label-width="auto" style="max-width: 600px;">
        <el-form-item label="姓名" prop="name">
          <el-input maxlength="255" v-model="role.name" placeholder="请输入角色姓名"></el-input>
        </el-form-item>
        <el-form-item label="描述" prop="description">
          <el-input type="textarea" rows="5" maxlength="255" v-model="role.description" placeholder="请输入描述"></el-input>
        </el-form-item>
        <el-button style="margin-left: 70px;" @click="save">提交</el-button>
        <el-button @click="empty">清空</el-button>
      </el-form>
  </div>
</template>
<script setup>
import { _axios,get,post } from '@/plugins/axios' 
import { ref,reactive } from 'vue'
import path from "./path"
// 子组件和组件共享数据和函数
const emits = defineEmits(['update:show','getTableData'])
// 父组件向子组件传递数据
const props = defineProps(['id'])
// 用来保存表单数据
const role = reactive({
  id:null,
  name: '',
  description:'',
  state:0,
  file: null,
  icno:null
})
function check(rule,value,callback){
  let params = {
    column: rule.fieldName,
    value,
    id: props.id
  }
  get(path.check,params,content => {
    // content == response.data.content
    if(content){
      // 可用
      callback()
    } else {
      // 不可用
      callback(new Error())
    }
  })
}
// 校验相关  
const rules = {  
 name:[
    // 校验是否为空
    { required: true, message: '请输入姓名',trigger: 'blur'},
    { validator: check,message: '该名字已经被占用',trigger: 'blur', fieldName: 'name'}
  ],
  description:[
    { required: true, message: '请输入描述',trigger: 'blur'}
  ],
};  
// 表单对象
const formObj = ref()
console.log(props.id)
if(props.id){
  role.id = props.id
  getById()
}
// 重置表单
function empty(){
  role.name = ''
  role.description = ''
  role.state = ''
}
function getById(){
  console.log(props.id)
  get(path.get,{id:props.id},function(content){
     for(let key in role){
      // 将后端没有的属性的数据排除掉
      if(Object.prototype.hasOwnProperty.call(content,key)){
        role[key] = content[key]
      }
    }
    fileList.push({
      url: path.image + content.icno
    })
  })
}
// 表单提交
function save(){
  post(props.id ? path.update : path.add,role,content => {
        emits('update:show', false)
        emits('getTableData')
      },formObj)
}
</script>
<style scoped lang='scss'>

</style>